import { useState, useEffect } from "react";
import { Modal, Table, message } from "antd";
import { ColumnsType } from "antd/es/table";
import { groupMembers } from "@api/group";


interface MembersModalProps {
    isOpen: boolean;
    chatroomId: number;
    handleClose: () => void;
    queryKey: string;
}
interface User {
    id: number;
    username: string;
    nickName: string;
    headPic: string;
    email: string;
}

const columns: ColumnsType<User> = [
    {
        title: 'ID',
        dataIndex: 'id'
    },
    {
        title: '用户名',
        dataIndex: 'username'
    },
    {
        title: '昵称',
        dataIndex: 'nickName'
    },
    {
        title: '头像',
        render: (_, record) => {
            return <div>
                <img src={record.headPic} width={50} height={50} alt="" />
            </div>
        }
    },
    {
        title: '邮箱',
        dataIndex: 'email'
    }
];

export function MembersModal(props: MembersModalProps) {
    const [members, setMembers] = useState<Array<User>>([]);

    const queryMembers = async () => {
        try {
            const resp: any = await groupMembers(props.chatroomId);
            setMembers(resp.map((item: User) => {
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }

    useEffect(() => {
        queryMembers();
    }, [props.chatroomId, props.queryKey])

    return <Modal
        open={props.isOpen}
        onCancel={props.handleClose}
        onOk={props.handleClose}
        title='群聊成员'
        width={1000}
    >
        <Table columns={columns} dataSource={members} pagination={false}></Table>
    </Modal>
}